package com.javahash.spring.service;

import org.json.simple.JSONValue;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class APIExchangeRates {


    public Map<String, Double> getExchangeRates() {

        RestTemplate restTemplate = new RestTemplate();


        HashMap<String, Double> exchangeRates = new HashMap<>();
        ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity("https://bitpay.com/api/rates", Object[].class);


        Object[] linkedHashMapArray = responseEntity.getBody();

        for (Object o : linkedHashMapArray) {


            LinkedHashMap linkedHashMap = (LinkedHashMap) o;
            String code = (String) linkedHashMap.get("code");
            Double rate = Double.valueOf(linkedHashMap.get("rate").toString());

            exchangeRates.put(code, rate);


        }
        exchangeRates.put("BTC", 1.0);


        return exchangeRates;


    }


    public String getExchangeRatesJson() {

        return JSONValue.toJSONString(getExchangeRates());
    }


}

